package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.common.utils.RedisUtil;
import com.example.lotterysystem.controller.param.CreateActivityParam;
import com.example.lotterysystem.controller.param.CreatePrizeByActivityParam;
import com.example.lotterysystem.controller.param.CreateUserByActivityParam;
import com.example.lotterysystem.controller.param.PageParam;
import com.example.lotterysystem.dao.dataobject.ActivityDo;
import com.example.lotterysystem.dao.dataobject.ActivityPrizeDo;
import com.example.lotterysystem.dao.dataobject.ActivityUserDo;
import com.example.lotterysystem.dao.dataobject.PrizeDo;
import com.example.lotterysystem.dao.mapper.*;
import com.example.lotterysystem.service.ActivityService;
import com.example.lotterysystem.service.dto.ActivityDTO;
import com.example.lotterysystem.service.dto.ActivityDetailDTO;
import com.example.lotterysystem.service.dto.CreateActivityDTO;

import com.example.lotterysystem.service.dto.PageListDTO;
import com.example.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.example.lotterysystem.service.enums.ActivityPrizeTiersEnum;
import com.example.lotterysystem.service.enums.ActivityStatusEnum;
import com.example.lotterysystem.service.enums.ActivityUserStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements ActivityService {

    private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);
    /**
     * 活动缓存前置，为了区分业务
     */
    private final String ACTIVITY_PREFIX = "ACTIVITY_";
    /**
     * 活动缓存过期时间
     */
    private final Long ACTIVITY_TIMEOUT = 60 * 60 * 24 * 3L;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PrizeMapper prizeMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;
    @Autowired
    private ActivityUserMapper activityUserMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CreateActivityDTO createActivity(CreateActivityParam param) {
        checkActivityInfo(param);
        ActivityDo activityDo = new ActivityDo();
        activityDo.setActivityName(param.getActivityName());
        activityDo.setDescription(param.getDescription());
        activityDo.setStatus(ActivityStatusEnum.RUNNING.name());
        activityMapper.insert(activityDo);
        //保存活动关联的奖品
        List<CreatePrizeByActivityParam> prizeParams = param.getActivityPrizeList();
        List<ActivityPrizeDo> activityPrizeDOList = prizeParams.stream()
                .map(prizeParam -> {
                    ActivityPrizeDo activityPrizeDo = new ActivityPrizeDo();
                    activityPrizeDo.setActivityId(activityDo.getId());
                    activityPrizeDo.setPrizeId(prizeParam.getPrizeId());
                    activityPrizeDo.setPrizeAmount(prizeParam.getPrizeAmount());
                    activityPrizeDo.setPrizeTiers(prizeParam.getPrizeTiers());
                    activityPrizeDo.setStatus(ActivityPrizeStatusEnum.INIT.name());
                    return activityPrizeDo;
                }).collect(Collectors.toList());
        activityPrizeMapper.batchInsert(activityPrizeDOList);
        //保存活动关联的人员信息
        List<CreateUserByActivityParam> userParams = param.getActivityUserList();
        List<ActivityUserDo> activityUserDOList = userParams.stream()
                .map(userParam -> {
                    ActivityUserDo activityUserDO = new ActivityUserDo();
                    activityUserDO.setActivityId(activityDo.getId());
                    activityUserDO.setUserId(userParam.getUserId());
                    activityUserDO.setUserName(userParam.getUserName());
                    activityUserDO.setStatus(ActivityUserStatusEnum.INIT.name());
                    return activityUserDO;
                }).collect(Collectors.toList());
        activityUserMapper.batchInsert(activityUserDOList);

        //整合完信息，存放redis中
        List<Long> prizeId = param.getActivityPrizeList().stream()
                .map(CreatePrizeByActivityParam::getPrizeId)
                .distinct()
                .collect(Collectors.toList());
        List<PrizeDo> prizeDoList = prizeMapper.batchSelectByIds(prizeId);
        ActivityDetailDTO detailDTO = convertToActivityDetailDTO(activityDo, activityUserDOList,
                prizeDoList, activityPrizeDOList);
        cacheActivity(detailDTO);
        CreateActivityDTO createActivityDTO = new CreateActivityDTO();
        createActivityDTO.setActivityId(activityDo.getId());
        return createActivityDTO;
    }

    @Override
    public PageListDTO<ActivityDTO> findActivityList(PageParam param) {
        int total = activityMapper.count();
        List<ActivityDo> activityDoList = activityMapper.selectActivityList(param.offset(), param.getPageSize());
        List<ActivityDTO> activityDTOList = activityDoList.stream()
                .map(activityDo -> {
                    ActivityDTO activityDTO = new ActivityDTO();
                    activityDTO.setActivityId(activityDo.getId());
                    activityDTO.setActivityName(activityDo.getActivityName());
                    activityDTO.setDescription(activityDo.getDescription());
                    activityDTO.setStatus(ActivityStatusEnum.forName(activityDo.getStatus()));
                    return activityDTO;
                }).collect(Collectors.toList());
        return new PageListDTO<>(total , activityDTOList);
    }

    @Override
    public ActivityDetailDTO getActivityDetail(Long activityId) {
        //校验参数
        if(activityId == null){
            logger.warn("要查询的活动不存在 activityId为空");
            return null;
        }
        // 查询 redis
        ActivityDetailDTO detailDTO = getActivityFromCache(activityId);
        if (null != detailDTO) {
            logger.info("查询活动详细信息成功！detailDTO={}",
                    JacksonUtil.writeValueAsString(detailDTO));
            return detailDTO;
        }
        // 如果redis不存在，查表
        // 活动表
        ActivityDo activityDo = activityMapper.selectById(activityId);
        // 活动奖品表
        List<ActivityPrizeDo> apDOList =  activityPrizeMapper.selectByActivityId(activityId);
        // 活动人员表
        List<ActivityUserDo> auDOList = activityUserMapper.selectByActivityId(activityId);
        // 奖品表: 先获取要查询的奖品id
        List<Long> prizeIds = apDOList.stream()
                .map(ActivityPrizeDo::getPrizeId)
                .collect(Collectors.toList());
        List<PrizeDo> pDOList = prizeMapper.batchSelectByIds(prizeIds);
        // 整合活动详细信息，存放redis
        detailDTO =  convertToActivityDetailDTO(activityDo , auDOList , pDOList , apDOList);
        cacheActivity(detailDTO);
        return detailDTO;
    }

    @Override
    public void cacheActivity(Long activityId) {

        if(activityId == null){
            logger.error("activityId为空");
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_ERROR);
        }

        // 如果redis不存在，查表
        // 活动表
        ActivityDo activityDo = activityMapper.selectById(activityId);
        if(activityDo == null){
            logger.error("activityId传入错误");
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_ERROR);
        }

        // 活动奖品表
        List<ActivityPrizeDo> apDOList =  activityPrizeMapper.selectByActivityId(activityId);
        // 活动人员表
        List<ActivityUserDo> auDOList = activityUserMapper.selectByActivityId(activityId);
        // 奖品表: 先获取要查询的奖品id
        List<Long> prizeIds = apDOList.stream()
                .map(ActivityPrizeDo::getPrizeId)
                .collect(Collectors.toList());
        List<PrizeDo> pDOList = prizeMapper.batchSelectByIds(prizeIds);
        // 整合活动详细信息，存放redis

        cacheActivity(convertToActivityDetailDTO(activityDo , auDOList , pDOList , apDOList));
    }

    /**
     * 根据活动id从缓存中获取活动详细信息
     *
     * @param activityId
     * @return
     */
    private ActivityDetailDTO getActivityFromCache(Long activityId) {
        if (null == activityId) {
            logger.warn("获取缓存活动数据的activityId为空！");
            return null;
        }
        try {
            String str = redisUtil.get(ACTIVITY_PREFIX + activityId);
            if (!StringUtils.hasText(str)) {
                logger.info("获取的缓存活动数据为空！key={}", ACTIVITY_PREFIX + activityId);
                return null;
            }
            return JacksonUtil.readValue(str, ActivityDetailDTO.class);
        } catch (Exception e) {
            logger.error("从缓存中获取活动信息异常，key={}", ACTIVITY_PREFIX + activityId, e);
            return null;
        }

    }

    /**
     * 缓存完整的活动信息 ActivityDetailDTO
     *
     * @param detailDTO
     */
    public void cacheActivity(ActivityDetailDTO detailDTO) {
        // key: ACTIVITY_12
        // value: ActivityDetailDTO(json)
        if(detailDTO == null || detailDTO.getActivityId() == null){
            logger.warn("要缓存的信息不存在");
        }
        try {
            redisUtil.set(ACTIVITY_PREFIX + detailDTO.getActivityId() ,
                    JacksonUtil.writeValueAsString(detailDTO) ,
                    ACTIVITY_TIMEOUT);
        }catch (Exception e){
            logger.error("缓存活动异常，ActivityDetailDTO={}",
                    JacksonUtil.writeValueAsString(detailDTO),
                    e);
        }

    }

    private ActivityDetailDTO convertToActivityDetailDTO(ActivityDo activityDo,
                                                         List<ActivityUserDo> activityUserDOList,
                                                         List<PrizeDo> prizeDoList,
                                                         List<ActivityPrizeDo> activityPrizeDOList) {
        ActivityDetailDTO detilDTO = new ActivityDetailDTO();
        detilDTO.setActivityId(activityDo.getId());
        detilDTO.setActivityName(activityDo.getActivityName());
        detilDTO.setDesc(activityDo.getDescription());
        detilDTO.setStatus(ActivityStatusEnum.forName(activityDo.getStatus()));

        List<ActivityDetailDTO.PrizeDTO> prizeDTOList = activityPrizeDOList
                .stream()
                .map(apDO->{
                   ActivityDetailDTO.PrizeDTO prizeDTO = new ActivityDetailDTO.PrizeDTO();
                   prizeDTO.setPrizeId(apDO.getPrizeId());
                    Optional<PrizeDo> optionalPrizeDo = prizeDoList.stream()
                            .filter(prizeDo -> prizeDo.getId().equals(apDO.getPrizeId()))
                            .findFirst();
                    optionalPrizeDo.ifPresent(prizeDo -> {
                        prizeDTO.setName(prizeDo.getName());
                        prizeDTO.setImageUrl(prizeDo.getImageUrl());
                        prizeDTO.setPrice(prizeDo.getPrice());
                        prizeDTO.setDescription(prizeDo.getDescription());
                    });
                    prizeDTO.setTiers(ActivityPrizeTiersEnum.forName(apDO.getPrizeTiers()));
                    prizeDTO.setPrizeAmount(apDO.getPrizeAmount());
                    prizeDTO.setStatus(ActivityPrizeStatusEnum.forName(apDO.getStatus()));
                    return prizeDTO;
                }).collect(Collectors.toList());
        detilDTO.setPrizeDTOList(prizeDTOList);

        List<ActivityDetailDTO.UserDTO> userDTOList = activityUserDOList.stream()
                .map(auDO -> {
                    ActivityDetailDTO.UserDTO userDTO = new ActivityDetailDTO.UserDTO();
                    userDTO.setUserId(auDO.getUserId());
                    userDTO.setUserName(auDO.getUserName());
                    userDTO.setStatus(ActivityUserStatusEnum.forName(auDO.getStatus()));
                    return userDTO;
                }).collect(Collectors.toList());
        detilDTO.setUserDTOList(userDTOList);
        return detilDTO;
    }


    private void checkActivityInfo(CreateActivityParam param) {
        if(param == null){
            throw new ServiceException(ServiceErrorCodeConstants.CREATE_ACTIVITY_INFO_IS_EMPTY);
        }
        //判断参与活动的人员是否正确
        List<Long> userIds = param.getActivityUserList().stream()
                .map(CreateUserByActivityParam::getUserId)
                .distinct()
                .collect(Collectors.toList());
        List<Long> exixtUserIds = userMapper.selectExistByIds(userIds);
        if(CollectionUtils.isEmpty(exixtUserIds)){
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
        }
        userIds.forEach(id ->{
            if(!exixtUserIds.contains(id)){
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
            }
        });

        // 奖品id在奖品表中是否存在
        List<Long> prizeIds = param.getActivityPrizeList().stream()
                .map(CreatePrizeByActivityParam::getPrizeId)
                .distinct()
                .collect(Collectors.toList());
        List<Long> existPrizeIds = prizeMapper.selectExistByIds(prizeIds);
        if(CollectionUtils.isEmpty(existPrizeIds)){
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
        }
        prizeIds.forEach(id ->{
            if(!existPrizeIds.contains(id)){
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
            }
        });
        // 人员数量大于等于奖品数量
        // 2个奖品 2 1
        int userAmount = param.getActivityUserList().size();
        long prizeAmount = param.getActivityPrizeList()
                .stream()
                .mapToLong(CreatePrizeByActivityParam::getPrizeAmount) // 2 1
                .sum();
        if (userAmount < prizeAmount) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_PRIZE_AMOUNT_ERROR);
        }

        // 校验活动奖品等奖有效性
        param.getActivityPrizeList().forEach(prize -> {
            if (null == ActivityPrizeTiersEnum.forName(prize.getPrizeTiers())) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_TIERS_ERROR);
            }
        });
    }
}






















